import dayjs from "dayjs";
import { GetPage, Save, Delete } from "@/api/teacher/arrange";
import {
  TaskDisEnableOrEnable,
  TaskGetone,
  Update,
  TaskClose
} from "@/api/teacher/task";
import { ClassGetAll } from "@/api/teacher/zsclass";
import { PlanGetPage } from "@/api/teacher/plan";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import qs from "qs";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
export function useArrange() {
  const form = reactive({
    TaskArrangementId: 0, //主键id
    planId: undefined, //计划Id
    classId: undefined, //班级Id
    startTime: "", //开始时间
    TestDuration: 0, //TestDuration
    remark: "", //Remark
    taskType: 0
  });
  const classNameSelect = ref<any>([]);
  const dataList = ref<any>([]);
  const loading = ref(false);
  const oncData = reactive({
    classId: 0,
    planId: 0
  });
  const req = ref(undefined);
  const isShow = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref(undefined);
  const PlanList = ref<any>([]);
  const rules = {
    planId: [
      {
        required: true,
        message: "请输入计划名称！",
        trigger: ["blur", "change"]
      }
    ],
    createUser: [
      {
        required: true,
        message: "请输入用户数量！",
        trigger: ["blur", "change"]
      }
    ],
    startTime: [
      {
        required: true,
        message: "请选择开始时间！",
        trigger: ["blur", "change"]
      }
    ],
    TestDuration: [
      {
        required: true,
        message: "请输入时长！",
        trigger: ["blur", "change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "计划名称",
      prop: "planName",
      minWidth: 100
    },
    {
      label: "班级名称",
      prop: "className",
      minWidth: 100
    },
    {
      label: "开始时间",
      minWidth: 180,
      prop: "startTime",
      formatter: ({ startTime }) =>

        startTime ? dayjs(startTime).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "时长（分钟）",
      prop: "testDuration",
      cellRenderer: ({ row }) => (
        <span> {row.taskType == 1 ? "" : row.testDuration} </span>
      )
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={row.status === 0 ? "danger" : ""} effect="plain">
          {row.status === 1 ? "激活" : "未激活"}
        </el-tag>
      )
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 280,
      slot: "operation"
    }
  ];
  /**
   * 测试时长输入监控
   * @param e 事件
   */
  async function testDurationHandleKeyDown(e: any) {
    if (e.key === 'e' || e.key === 'E') {
      e.preventDefault();//阻止默认行为，阻止'e'字符的输入
    }
  }
  async function handleUpdate(row: any | undefined) {
    updatePanelVisible.value = true;
    getPlanList();
    console.log("row", row)
    if (row) {
      loadingTitle.value = "修改";
      const data = qs.stringify({
        id: row.taskArrangementId
      });
      const res = await TaskGetone(data);
      oncData.classId = res.data.classId;
      oncData.planId = res.data.planId;
      nextTick(() => {
        form.TaskArrangementId = row.taskArrangementId;
        form.planId = row.planName;
        form.startTime = row.startTime;
        form.TestDuration = row.testDuration;
        form.remark = row.remark;
        form.taskType = row.taskType;
      });
      isShow.value = true;
    } else {
      loadingTitle.value = "添加";
      oncData.classId = 0;
      oncData.planId = 0;
      form.TaskArrangementId = 0;
      isShow.value = false;
    }
  }

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const respone = await Delete(row.taskArrangementId);
      if (respone.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }

    }).catch(() => { })

  }

  function handleSizeChange(val: number) {
    // console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    // console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  //获取任务列表
  async function onSearch() {
    loading.value = true;
    const res = await GetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      classId: form.classId
    });
    if (res.data.list.length) {
      dataList.value = res.data.list;
      pagination.total = res.data.totalCount;
      loading.value = false;

      // pagination.total = parseInt(data.totalCount);
    } else {
      ElMessage.warning(res?.msg);
      dataList.value = res.data.list;
      loading.value = false;
    }
  }

  //初始化班级名称下拉框
  async function initSelect() {
    const response = await ClassGetAll();
    if (response.success == true) {
      classNameSelect.value = response.data;
    }
  }

  //添加 or 修改任务安排信息
  const addOrEditTaskArrange = async (DtoRef: FormInstance | undefined) => {
    if (form.TaskArrangementId) {
      const req = await Update({
        ...form,
        classId: oncData.classId,
        planId: oncData.planId
      });
      updatePanelVisible.value = false;
      onSearch();
      ElMessage.success(req.msg);
      DtoRef.resetFields();
    } else {
      (DtoRef as any).validate(async valid => {
        if (!valid) return;
        const isform = {
          ...form,
          planId: form.planId.planId ?? 0,
        }
        const req = await Save(isform);
        if (req.status == 200) {
          updatePanelVisible.value = false;
          onSearch();
        }
        ElMessage.success(req.msg);
      });
    }
  };
  // 获取计划名称列表
  async function getPlanList() {
    const data = {
      pageSize: 1000,
      currentPage: 1,
    }
    const respone = await PlanGetPage(data);
    if (respone.success) {
      PlanList.value = respone?.data?.items;
    }
  }

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    if (!row) return;
    row.resetFields();
    form.taskType = 0;
    updatePanelVisible.value = false;
  }

  //修改状态
  async function activation(row: any) {
    // const qr =
    //   row.status == 1
    //     ? { id: row.taskArrangementId }
    //     : { id: row.taskArrangementId, isEnable: !row.status };
    // const data = qs.stringify(qr);
    // switch (row.status) {
    //   case 1:
    //     req.value = await TaskClose(data);
    //     break;
    //   case 0:
    //     req.value = await TaskDisEnableOrEnable(data);
    //     break;
    // }
    // ElMessage.success(req.value.msg);
    // onSearch();
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: `是否确定${row.status ? "关闭" : "激活"}当前状态?`, //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const qr =
        row.status == 1
          ? { id: row.taskArrangementId }
          : { id: row.taskArrangementId, isEnable: !row.status };
      const data = qs.stringify(qr);
      switch (row.status) {
        case 1:
          req.value = await TaskClose(data);
          break;
        case 0:
          req.value = await TaskDisEnableOrEnable(data);
          break;
      }
      ElMessage.success(req.value.msg);
      onSearch();

    }).catch(() => { })
  }
  // const resetForm = formEl => {
  //   formEl.resetFields();
  //   updatePanelVisible.value = false;
  // };

  onMounted(() => {
    initSelect();
  });

  return {
    form,
    PlanList,
    loading,
    columns,
    dataList,
    // addDtoRef,
    pagination,
    loadingTitle,
    isShow,
    updatePanelVisible,
    rules,
    classNameSelect,
    onSearch,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    handleSelectionChange,
    addOrEditTaskArrange,
    activation,
    testDurationHandleKeyDown
  };
}
